package level.model;

import java.util.HashMap;
import java.util.Map;

public class GameObject implements Addable
{
	public GameObject()
	{
		components = new HashMap<String, Component>();
		iconPath = null;
		x = 0;
		y = 0;
	}
	
	public void setObjectName(String name)
	{
		this.objectName = name;
	}
	
	public String getObjectName()
	{
		return objectName;
	}

	public void addComponent(Component c)
	{
		components.put(c.getComponentName(), c);
	}

	public Component getComponent(String search)
	{
		return components.get(search);
	}

	public Map<String, Component> getComponents()
	{
		return components;
	}

	public String getIconPath()
	{
		return iconPath;
	}

	public void setIconPath(String iconPath)
	{
		this.iconPath = iconPath;
	}

	public int getX()
	{
		return x;
	}

	public void setX(int x)
	{
		this.x = x;
		Component comp = getComponent("PositionComponent");
		if (comp != null)
		{
			comp.getAttribute("x").setValue("" + x);
		}
	}

	public int getY()
	{
		return y;
	}

	public void setY(int y)
	{
		this.y = y;
		Component comp = getComponent("PositionComponent");
		if (comp != null)
		{
			comp.getAttribute("y").setValue("" + y);
		}
	}

	public int getW()
	{
		return w;
	}

	public void setW(int w)
	{
		this.w = w;
	}

	public int getH()
	{
		return h;
	}

	public void setH(int h)
	{
		this.h = h;
	}

	@Override
	public boolean equals(Addable addable)
	{
		GameObject gObject = (GameObject) addable;
		
		if (!objectName.equals(gObject.getObjectName()))
			return false;

		if (components.size() == gObject.getComponents().size())
		{
			for (String name : components.keySet())
			{
				if (!gObject.getComponents().containsKey(name)
						|| !(gObject.getComponents().get(name)
								.equals(components.get(name))))
				{
					return false;
				}
			}
			if (x == gObject.getX() && y == gObject.getY()
					&& w == gObject.getW() && h == gObject.getH()
					&& iconPath.equals(gObject.getIconPath()))
				return true;
		}
		return false;
	}

	@Override
	public Addable cloneAddable()
	{
		return cloneObject();
	}

	public GameObject cloneObject()
	{
		GameObject gObject = new GameObject();
		gObject.setIconPath(iconPath);
		gObject.setObjectName(objectName);
		gObject.setX(x);
		gObject.setY(y);
		gObject.setW(w);
		gObject.setH(h);
		for (String name : components.keySet())
		{
			gObject.addComponent((Component) components.get(name)
					.cloneAddable());
		}
		return gObject;
	}

	private Map<String, Component> components;
	private String iconPath;
	private String objectName;
	private int x;
	private int y;
	private int w;
	private int h;
}
